package com.wd.live.ui.activity

import android.os.Bundle
import android.view.SurfaceView
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.alipay.sdk.app.EnvUtils
import com.alipay.sdk.app.PayTask
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.opensource.svgaplayer.SVGACallback
import com.wd.live.BaseConstant
import com.wd.live.R
import com.wd.live.databinding.ActivityLookLiveBinding
import com.wd.live.tool.LocalData
import com.wd.live.tool.getUserId
import com.wd.live.tool.longToast
import com.wd.live.tool.viewBinding
import com.wd.live.ui.dailog.GiftListDialog
import com.wd.live.viewmodel.OpenLiveViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas

class LookLiveActivity : AppCompatActivity() {

    private var currentLiveId: Int? = null
    private var mRtcEngine: RtcEngine? = null
    private val binding: ActivityLookLiveBinding by viewBinding()
    val viewModel: OpenLiveViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_look_live)
        //初始化沙箱支付
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX)
        val data = intent.getParcelableExtra<LocalData.LiveShow>("live_data")
        XXPermissions.with(this).permission(Permission.RECORD_AUDIO, Permission.CAMERA)
            .request { permissions, all ->

                if (!all) {
                    longToast("获取部分权限成功，但部分权限未正常授予")
                }
                viewModel.lookLive(data?.liveId)
            }
        viewModel.lookLiveData.observe(this) { lookLiveInfo ->
            if (lookLiveInfo.channelName != null && lookLiveInfo.liveId != null && lookLiveInfo.agoraToken != null) {
                currentLiveId = lookLiveInfo.liveId
                initializeAndJoinChannel(
                    lookLiveInfo.channelName,
                    lookLiveInfo.liveId,
                    lookLiveInfo.agoraToken
                )
                //webSocket
                lookLiveInfo.compositeWsUrl?.let {
                    viewModel.connectSocket(it, applicationContext)
                }
            }
        }
        //发起连麦申请
        binding.link.setOnClickListener {
            currentLiveId?.let {
                viewModel.requestLink(it)
            }

        }
        //获取礼物列表
        binding.gift.setOnClickListener {
            //请求礼物数据
            viewModel.getGiftList()
        }

        //充值
        binding.recharge.setOnClickListener {
            viewModel.recharge()
        }

        viewModel.giftInfo.observe(this) { giftInfo ->
            try {
                //打开礼物Dialog
                GiftListDialog(this@LookLiveActivity, giftInfo) {
                    //调用送礼接口
                    viewModel.sendGift(it, currentLiveId)
                }.show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        viewModel.payMsg.observe(this) {

            Thread {
                val alipay = PayTask(this)
                val result: Map<String, String> = alipay.payV2(it, true)
                runOnUiThread {
                    longToast(result.toString())
                }
            }.start()
        }

        //播放礼物动画
        viewModel.giftName.observe(this) {

            binding.giftSvga.callback = object : SVGACallback {
                override fun onFinished() {
                    //停止动画
                    binding.giftSvga.stopAnimation()
                }

                override fun onPause() {
                }

                override fun onRepeat() {
                }

                override fun onStep(frame: Int, percentage: Double) {
                }

            }
            //开启动画
            binding.giftSvga.startAnimation()
        }

        //主播同意连麦，设置本地视频数据
        viewModel.agreeLink.observe(this) {
            getUserId()?.let { it1 -> setUpLocal(it1) }
        }
    }



    private fun setUpLocal(userId: Int) {
        val surfaceView = SurfaceView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
        binding.localVideoViewContainer.visibility = View.VISIBLE
        binding.localVideoViewContainer.addView(surfaceView)
        mRtcEngine?.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, userId))
        //角色进行变化，CLIENT_ROLE_BROADCASTER
        mRtcEngine?.setClientRole(Constants.CLIENT_ROLE_BROADCASTER)
    }

    private fun initializeAndJoinChannel(channelName: String, liveId: Int, agoraToken: String) {

        try {
            val config = RtcEngineConfig()
            config.mContext = baseContext
            config.mAppId = BaseConstant.OPEN_LIVE_ID
            config.mEventHandler = object : IRtcEngineEventHandler() {

                override fun onUserJoined(uid: Int, elapsed: Int) {
                    super.onUserJoined(uid, elapsed)
                    runOnUiThread {
                        // 从 onUserJoined 回调获取 uid 后，调用 setupRemoteVideo，设置远端视频视图。
                        setupRemoteVideo(uid)
                    }
                }
                override fun onJoinChannelSuccess(channel: String?, uid: Int, elapsed: Int) {
                    super.onJoinChannelSuccess(channel, uid, elapsed)
                }
            }
            mRtcEngine = RtcEngine.create(config)?.apply {
                enableVideo()
                //设置成为观众
                setClientRole(Constants.CLIENT_ROLE_AUDIENCE)
                setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING)
                // 服务端接口返回的 token，channelName,以及我们的登陆信息userId
                val options = ChannelMediaOptions()
                options.autoSubscribeAudio = true
                options.autoSubscribeVideo = true
                joinChannel(agoraToken, channelName, getUserId() ?: 0, options)
            }
        } catch (e: Exception) {
            throw RuntimeException("Check the error.")
        }
    }

    private fun setupRemoteVideo(uid: Int) {
        val surfaceView = SurfaceView(baseContext)
        surfaceView.setZOrderMediaOverlay(true)
        binding.remoteVideoViewContainer.addView(surfaceView)
        mRtcEngine?.setupRemoteVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, uid))
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        mRtcEngine?.stopPreview()
        mRtcEngine?.leaveChannel()
        //关闭连接
        viewModel.closeWebSocket()
    }
}